<template>
  <div>
    <!-- 验收弹窗 -->
    <a-modal v-model:visible="visible" v-if="showNum === 0" title="验收" @ok="handleAcceptanceOk" @cancel="handleCancel"
      :confirmLoading="confirmLoading" :maskClosable="false" width="840px">
      <a-form ref="acceptanceFormRef" :model="acceptanceForm" :rules="acceptanceRules" :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }">
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 验收日期 -->
            <a-form-item label="验收日期" name="acceptanceDate">
              <a-date-picker v-model:value="acceptanceForm.acceptanceDate" :disabled-date="disabledDate"
                style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 验收人员 -->
            <a-form-item label="验收人员" name="inspector">
              <a-select v-model:value="acceptanceForm.inspector" show-search :filter-option="false"
                :loading="userLoading" @search="handleUserSearch" placeholder="请输入姓名搜索">
                <a-select-option v-for="user in userOptions" :key="user.id" :value="user.id">
                  {{ user.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 合格数量 -->
            <a-form-item label="合格数量" name="qualifiedQuantity">
              <a-input-number v-model:value="acceptanceForm.qualifiedQuantity" :min="0" style="width: 100%"
                placeholder="请输入合格数量" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 不合格数量 -->
            <a-form-item label="不合格数量" name="unqualifiedQuantity">
              <a-input-number v-model:value="acceptanceForm.unqualifiedQuantity" :min="0" style="width: 100%"
                placeholder="请输入不合格数量" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 报废数量 -->
            <a-form-item label="报废数量" name="scrapQuantity">
              <a-input-number v-model:value="acceptanceForm.scrapQuantity" :min="0" style="width: 100%"
                placeholder="请输入报废数量" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 备注 -->
            <a-form-item label="备注" name="note">
              <a-textarea v-model:value="acceptanceForm.note" :maxlength="200" :rows="1" show-count
                placeholder="请输入备注信息（最多200字）" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 入库弹窗 -->
    <a-modal v-model:visible="visible" v-if="showNum === 1" title="入库" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel" :maskClosable="false" width="800px">
      <a-form ref="stockInFormRef" :model="stockInForm" :rules="stockInRules" :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }">
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 商品编号 -->
            <a-form-item label="商品编号">
              <a-input v-model:value="stockInForm.productCode" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 商品名称 -->
            <a-form-item label="商品名称">
              <a-input v-model:value="stockInForm.productName" disabled />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 合格数量 -->
            <a-form-item label="合格数量">
              <a-input-number v-model:value="stockInForm.qualifiedQuantity" disabled style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 已入库数量 -->
            <a-form-item label="已入库数量">
              <a-input-number v-model:value="stockInForm.stockedQuantity" disabled style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 仓库选择 -->
            <a-form-item label="入库仓库" name="warehouseId">
              <a-select v-model:value="stockInForm.warehouseId" show-search :filter-option="false"
                :loading="warehouseLoading" @search="handleWarehouseSearch" @change="handleWarehouseChange"
                placeholder="请输入仓库名称搜索">
                <a-select-option v-for="item in warehouseOptions" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 当前库存 -->
            <a-form-item label="当前库存">
              <a-input-number v-model:value="stockInForm.currentStock" disabled style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 本次入库 -->
            <a-form-item label="本次入库" name="stockInQuantity">
              <a-input-number v-model:value="stockInForm.stockInQuantity" :min="1"
                :max="stockInForm.qualifiedQuantity - stockInForm.stockedQuantity" style="width: 100%"
                placeholder="请输入入库数量" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 备注 -->
            <a-form-item label="备注" name="note">
              <a-textarea v-model:value="stockInForm.note" :maxlength="200" :rows="1" show-count
                placeholder="请输入备注信息（最多200字）" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 领料弹窗 -->
    <a-modal v-model:visible="visible" title="领料" @ok="handlePickingOk" @cancel="handlePickingCancel"
      v-if="showNum === 2" :confirmLoading="confirmLoading" :maskClosable="false">
      <a-form ref="pickingFormRef" :model="pickingForm" :rules="pickingRules" :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }">
        <!-- 商品信息 -->
        <a-form-item label="商品编号">
          <a-input v-model:value="pickingForm.productCode" disabled />
        </a-form-item>
        <a-form-item label="商品名称">
          <a-input v-model:value="pickingForm.productName" disabled />
        </a-form-item>

        <!-- 仓库选择 -->
        <a-form-item label="物料仓库" name="productionStoreId">
          <a-select v-model:value="pickingForm.productionStoreId" show-search :filter-option="false"
            :loading="warehouseLoading" @search="handleWarehouseSearch" @change="handleWarehouseChange"
            placeholder="请输入仓库名称搜索">
            <a-select-option v-for="item in warehouseOptions" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 库存数量 -->
        <a-form-item label="当前库存">
          <a-input-number v-model:value="pickingForm.storeNumber" disabled />
        </a-form-item>

        <!-- 领料数量 -->
        <a-form-item label="本次领料" name="receiveNumber">
          <a-input-number v-model:value="pickingForm.receiveNumber" :min="1" :max="pickingForm.storeNumber"
            :precision="0" />
        </a-form-item>

        <!-- 领料单位 -->
        <a-form-item label="领料单位" name="materialUnit">
          <a-input v-model:value="pickingForm.materialUnit" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 退料弹窗 -->
    <a-modal v-model:visible="visible" v-if="showNum === 3" title="退料" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel" :maskClosable="false">
      <a-form ref="returnFormRef" :model="returnForm" :rules="returnRules" :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }">
        <!-- 商品信息 -->
        <a-form-item label="商品编号">
          <a-input v-model:value="returnForm.productCode" disabled />
        </a-form-item>
        <a-form-item label="商品名称">
          <a-input v-model:value="returnForm.productName" disabled />
        </a-form-item>

        <!-- 仓库选择 -->
        <a-form-item label="退料仓库" name="warehouseId">
          <a-select v-model:value="returnForm.warehouseId" show-search :filter-option="false"
            :loading="warehouseLoading" @search="handleWarehouseSearch" @change="handleWarehouseChange"
            placeholder="请输入仓库名称搜索">
            <a-select-option v-for="item in warehouseOptions" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 库存数量 -->
        <a-form-item label="当前库存">
          <a-input-number v-model:value="returnForm.currentStock" />
        </a-form-item>

        <!-- 可退数量 -->
        <a-form-item label="可退数量">
          <a-input-number v-model:value="returnForm.maxReturnQuantity" />
        </a-form-item>

        <!-- 退料数量 -->
        <a-form-item label="本次退料" name="returnQuantity">
          <a-input-number v-model:value="returnForm.returnQuantity" :min="0" :max="returnForm.maxReturnQuantity"
            :precision="0" />
        </a-form-item>

        <!-- 退料单位 -->
        <a-form-item label="退料单位" name="unit">
          <a-input v-model:value="returnForm.unit" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 用料弹窗 -->
    <a-modal v-model:visible="visible" v-if="showNum === 4" title="用料" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel" :maskClosable="false">
      <a-form ref="useFormRef" :model="useForm" :rules="useRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <!-- 商品信息 -->
        <a-form-item label="商品编号">
          <a-input v-model:value="useForm.productCode" disabled />
        </a-form-item>
        <a-form-item label="商品名称">
          <a-input v-model:value="useForm.productName" disabled />
        </a-form-item>

        <!-- 可用数量 -->
        <a-form-item label="可用数量">
          <a-input-number v-model:value="useForm.availableQuantity" disabled />
          <!-- <template #help>
            <span class="quantity-detail">
              领料数量: {{ useForm.pickingQuantity }} -
              已用数量: {{ useForm.usedQuantity }} -
              已退数量: {{ useForm.returnedQuantity }}
            </span>
          </template> -->
        </a-form-item>

        <!-- 用料数量 -->
        <a-form-item label="本次用料" name="useQuantity">
          <a-input-number v-model:value="useForm.useQuantity" :min="0" :max="useForm.availableQuantity" :precision="0"
            placeholder="请输入用料数量" />
        </a-form-item>

        <!-- 用料单位 -->
        <a-form-item label="单位" name="unit">
          <a-input v-model:value="useForm.unit" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed } from 'vue';
import { message } from 'ant-design-vue';
import { storeApi } from '/@/api/base-data/store-center';
import { tasksProductionApi } from '/@/api/base-data/product/production-tasks';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'OutDialog',
  setup() {
    const visible = ref(false);
    const confirmLoading = ref(false);
    const pickingVisible = ref(false);
    const returnVisible = ref(false);
    const data = ref({});
    const showNum = ref(0);
    const formData = reactive({
      checkQuantity: null,
      checkNote: '',
      storeQuantity: null,
      storeNote: '',
      receiveQuantity: null,
      receiver: '',
      receiveNote: '',
      returnQuantity: null,
      returner: '',
      returnReason: '',
      returnNote: '',
      useQuantity: null,
      user: '',
      useNote: '',
    });
    const rules = {
      checkQuantity: [{ required: true, message: '请输入验收数量' }],
      storeQuantity: [{ required: true, message: '请输入入库数量' }],
      receiveQuantity: [{ required: true, message: '请输入领料数量' }],
      receiver: [{ required: true, message: '请输入领料人' }],
      returnQuantity: [{ required: true, message: '请输入退料数量' }],
      returner: [{ required: true, message: '请输入退料人' }],
      returnReason: [{ required: true, message: '请选择退料原因' }],
      useQuantity: [{ required: true, message: '请输入用料数量' }],
      user: [{ required: true, message: '请输入用料人' }],
    };

    // 领料表单数据
    const pickingForm = reactive({
      productionStoreId: undefined,
      materialsId: '',
      productCode: '',
      productName: '',
      storeNumber: 0,
      receiveNumber: 1,
      productionTaskId: '',
      materialUnit: '',
    });

    // 仓库选择相关
    const warehouseLoading = ref(false);
    const warehouseOptions = ref([]);

    // 表单校验规则
    const pickingRules = {
      warehouseId: [{ required: true, message: '请选择仓库' }],
      receiveNumber: [{ required: true, message: '请输入领料数量' }],
    };

    // 退料表单数据
    const returnForm = reactive({
      productCode: '',
      productName: '',
      warehouseId: undefined,
      currentStock: 0,
      maxReturnQuantity: 0,
      returnQuantity: 0,
      unit: '',
    });

    // 表单校验规则
    const returnRules = {
      warehouseId: [{ required: true, message: '请选择仓库' }],
      returnQuantity: [
        { required: true, message: '请输入退料数量' },
        {
          validator: (_, value) => {
            if (value > returnForm.maxReturnQuantity) {
              return Promise.reject('退料数量不能超过可退数量');
            }
            return Promise.resolve();
          }
        }
      ],
    };

    // 用料表单数据
    const useForm = reactive({
      productCode: '',
      productName: '',
      pickingQuantity: 0,    // 领料数量
      usedQuantity: 0,       // 已用数量
      returnedQuantity: 0,   // 已退数量
      availableQuantity: 0,  // 可用数量
      useQuantity: 0,        // 本次用料
      unit: '',
    });

    // 表单校验规则
    const useRules = {
      useQuantity: [
        { required: true, message: '请输入用料数量' },
        {
          validator: (_, value) => {
            if (value > useForm.availableQuantity) {
              return Promise.reject('用料数量不能超过可用数量');
            }
            return Promise.resolve();
          }
        }
      ],
      unit: [{ required: true, message: '请输入单位' }],
    };

    // 验收表单数据
    const acceptanceForm = reactive({
      acceptanceDate: null,
      inspector: undefined,
      productionQuantity: 0,
      qualifiedQuantity: 0,
      unqualifiedQuantity: 0,
      scrapQuantity: 0,
      note: '',
    });

    // 用户搜索相关
    const userLoading = ref(false);
    const userOptions = ref([]);

    // 禁用过去的日期
    const disabledDate = (current: dayjs.Dayjs) => {
      return current && current < dayjs().startOf('day');
    };

    // 搜索用户
    const handleUserSearch = async (value: string) => {
      if (!value) return;
      try {
        userLoading.value = true;
        const res = await tasksProductionApi.searchUsers({ keyword: value });
        userOptions.value = res.data || [];
      } finally {
        userLoading.value = false;
      }
    };

    // 表单校验规则
    const acceptanceRules = {
      acceptanceDate: [{ required: true, message: '请选择验收日期' }],
      inspector: [{ required: true, message: '请选择验收人员' }],
      qualifiedQuantity: [
        { required: true, message: '请输入合格数量' },
        {
          validator: (_, value) => {
            if (value > acceptanceForm.productionQuantity) {
              return Promise.reject('合格数量不能大于生产数量');
            }
            return Promise.resolve();
          },
        },
      ],
      unqualifiedQuantity: [{ required: true, message: '请输入不合格数量' }],
      scrapQuantity: [{ required: true, message: '请输入报废数量' }],
    };

    // 搜索仓库
    const handleWarehouseSearch = async (value: string) => {
      // if (!value) return;
      try {
        warehouseLoading.value = true;
        // const res = await storeApi.queryWarehouse({ name: value });
        const res = {
          data: [
            { id: 1, name: '仓库1' },
            { id: 2, name: '仓库2' },
          ],
        };
        warehouseOptions.value = res.data || [];
      } finally {
        warehouseLoading.value = false;
      }
    };

    // 选择仓库后获取库存
    const handleWarehouseChange = async (warehouseId: string) => {
      try {
        // const res = await storeApi.getStock({
        //   warehouseId,
        //   productCode: pickingForm.productCode,
        // });
        const res = {
          data: {
            id: 1,
            name: '仓库1',
            quantity: 10,
          },
        };
        pickingForm.storeNumber = res.data?.quantity || 0;
      } catch (error) {
        console.error('获取库存失败:', error);
        message.error('获取库存失败');
      }
    };

    // // 选择仓库后获取库存
    // const handleReturnWarehouseChange = async (warehouseId: string) => {
    //   try {
    //     // const res = await storeApi.getStock({
    //     //   warehouseId,
    //     //   productCode: returnForm.productCode ,
    //     // });
    //     const res = {
    //       data: {
    //         id: 1,
    //         name: '仓库1',
    //         quantity: 10,
    //       },
    //     };
    //     returnForm.currentStock = res.data?.quantity || 0;
    //   } catch (error) {
    //     console.error('获取库存失败:', error);
    //     message.error('获取库存失败');
    //   }
    // };

    // 确认领料
    const handlePickingOk = async () => {
      try {

        // 调用领料 API
        await tasksProductionApi.receiveMaterials(pickingForm);

        message.success('领料成功');
        pickingVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('领料失败:', error);
        message.error('领料失败');
      } finally {
        confirmLoading.value = false;
      }
    };

    // 打开领料弹窗
    const showPickingModal = (row) => {
      pickingForm.productCode = row.code;
      pickingForm.productName = row.name;
      pickingForm.materialUnit = row.unit;
      pickingForm.materialsId = row.id;
      pickingForm.productionTaskId = row.material
      pickingVisible.value = true;
    };

    // 确认退料
    const handleReturnOk = async () => {
      try {
        await returnFormRef.value?.validate();
        confirmLoading.value = true;

        // 调用退料 API
        // await tasksProductionApi.returnMaterial({
        //   ...returnForm,
        //   taskId: currentTaskId.value,
        // });

        message.success('退料成功');
        returnVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('退料失败:', error);
        message.error('退料失败');
      } finally {
        confirmLoading.value = false;
      }
    };

    // 打开退料弹窗
    const showReturnModal = (row) => {
      returnForm.productCode = row.productCode;
      returnForm.productName = row.productName;
      returnForm.unit = row.unit;
      returnForm.maxReturnQuantity = row.pickingQuantity - row.usedQuantity;
      returnForm.returnQuantity = 0;
      returnVisible.value = true;
    };

    // 确认用料
    const handleUseOk = async () => {
      try {
        await useFormRef.value?.validate();
        confirmLoading.value = true;

        // 调用用料 API
        await tasksProductionApi.useMaterial({
          ...useForm,
          taskId: currentTaskId.value,
        });

        message.success('用料登记成功');
        useVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('用料登记失败:', error);
        message.error('用料登记失败');
      } finally {
        confirmLoading.value = false;
      }
    };

    // 打开用料弹窗
    const showUseModal = async (taskId: string) => {
      currentTaskId.value = taskId;
      try {
        // 获取任务详情
        const res = await tasksProductionApi.getById(taskId);
        const taskInfo = res.data;

        // 获取物料使用信息
        const materialInfo = await tasksProductionApi.getMaterialInfo(taskId);

        useForm.productCode = taskInfo.productCode;
        useForm.productName = taskInfo.productName;
        useForm.unit = taskInfo.unit;
        useForm.pickingQuantity = materialInfo.pickingQuantity || 0;
        useForm.usedQuantity = materialInfo.usedQuantity || 0;
        useForm.returnedQuantity = materialInfo.returnedQuantity || 0;

        // 计算可用数量
        useForm.availableQuantity =
          useForm.pickingQuantity - useForm.usedQuantity - useForm.returnedQuantity;

        useForm.useQuantity = 0; // 默认用料数量为0

        useVisible.value = true;
      } catch (error) {
        console.error('获取任务信息失败:', error);
        message.error('获取任务信息失败');
      }
    };

    // 确认验收
    const handleAcceptanceOk = async () => {
      try {
        await acceptanceFormRef.value?.validate();
        confirmLoading.value = true;

        // 调用验收 API
        await tasksProductionApi.acceptance({
          ...acceptanceForm,
          taskId: currentTaskId.value,
        });

        message.success('验收成功');
        acceptanceVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('验收失败:', error);
        message.error(error.message || '验收失败');
      } finally {
        confirmLoading.value = false;
      }
    };

    // 打开验收弹窗
    const showAcceptanceModal = async (taskId: string) => {
      currentTaskId.value = taskId;
      try {
        // 获取任务详情
        const res = await tasksProductionApi.getById(taskId);
        const taskInfo = res.data;

        acceptanceForm.productionQuantity = taskInfo.quantity;
        acceptanceForm.acceptanceDate = dayjs();
        acceptanceForm.qualifiedQuantity = 0;
        acceptanceForm.unqualifiedQuantity = 0;
        acceptanceForm.scrapQuantity = 0;
        acceptanceForm.note = '';

        acceptanceVisible.value = true;
      } catch (error) {
        console.error('获取任务信息失败:', error);
        message.error('获取任务信息失败');
      }
    };

    // 入库表单数据
    const stockInForm = reactive({
      productCode: '',
      productName: '',
      qualifiedQuantity: 0,
      stockedQuantity: 0,
      warehouseId: undefined,
      currentStock: 0,
      stockInQuantity: 0,
      note: '',
    });

    // 表单校验规则
    const stockInRules = {
      warehouseId: [{ required: true, message: '请选择入库仓库' }],
      stockInQuantity: [
        { required: true, message: '请输入入库数量' },
        {
          validator: (_, value) => {
            if (!value || value <= 0) {
              return Promise.reject('请输入入库数量');
            }
            const remainQuantity = stockInForm.qualifiedQuantity - stockInForm.stockedQuantity;
            if (value > remainQuantity) {
              return Promise.reject(`入库数量不能超过可入库数量(${remainQuantity})`);
            }
            return Promise.resolve();
          },
        },
      ],
    };

    // 确认入库
    const handleStockInOk = async () => {
      try {
        await stockInFormRef.value?.validate();
        confirmLoading.value = true;

        // 调用入库 API
        await tasksProductionApi.stockIn({
          ...stockInForm,
          taskId: currentTaskId.value,
        });

        message.success('入库成功');
        stockInVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('入库失败:', error);
        message.error(error.message || '入库失败');
      } finally {
        confirmLoading.value = false;
      }
    };

    // 打开入库弹窗
    const showStockInModal = async (taskId: string) => {
      currentTaskId.value = taskId;
      try {
        // 获取任务详情
        const res = await tasksProductionApi.getById(taskId);
        const taskInfo = res.data;

        stockInForm.productCode = taskInfo.productCode;
        stockInForm.productName = taskInfo.productName;
        stockInForm.qualifiedQuantity = taskInfo.qualifiedQuantity || 0;
        stockInForm.stockedQuantity = taskInfo.stockedQuantity || 0;
        stockInForm.warehouseId = undefined;
        stockInForm.currentStock = 0;
        stockInForm.stockInQuantity = 0;
        stockInForm.note = '';

        stockInVisible.value = true;
      } catch (error) {
        console.error('获取任务信息失败:', error);
        message.error('获取任务信息失败');
      }
    };

    return {
      visible,
      confirmLoading,
      data,
      showNum,
      formData,
      rules,
      pickingVisible,
      pickingForm,
      pickingRules,
      warehouseLoading,
      warehouseOptions,
      handleWarehouseSearch,
      handleWarehouseChange,
      handlePickingOk,
      handlePickingCancel: () => pickingVisible.value = false,
      showPickingModal,
      returnVisible: ref(false),
      returnForm,
      returnRules,
      // handleReturnWarehouseChange,
      handleReturnOk,
      handleReturnCancel: () => returnVisible.value = false,
      showReturnModal,
      useVisible: ref(false),
      useForm,
      useRules,
      handleUseOk,
      handleUseCancel: () => useVisible.value = false,
      showUseModal,
      acceptanceVisible: ref(false),
      acceptanceForm,
      acceptanceRules,
      userLoading,
      userOptions,
      disabledDate,
      handleUserSearch,
      handleAcceptanceOk,
      handleAcceptanceCancel: () => acceptanceVisible.value = false,
      showAcceptanceModal,
      stockInVisible: ref(false),
      stockInForm,
      stockInRules,
      handleStockInOk,
      handleStockInCancel: () => stockInVisible.value = false,
      showStockInModal,
    };
  },
  methods: {
    showModal(val, row) {
      this.visible = true;
      this.showNum = val;
      this.data = row;
      console.log('====================>', row);
      if (val === 2) {
        this.handleWarehouseSearch('');
        console.log('====================>', row);
        this.showPickingModal(row);
      }
      if (val === 3) {
        console.log('====================>', row);
        // this.handleReturnWarehouseChange('');
        this.handleWarehouseChange('');
        this.showReturnModal(row);
      }
      this.resetForm();
    },
    async handleOk() {
      try {
        await this.$refs.formRef.validate();
        this.confirmLoading = true;

        const apis = {
          0: () => tasksProductionApi.checkProcess(this.formData),
          1: () => tasksProductionApi.upStore(this.formData),
          2: () => tasksProductionApi.receiveMaterials(this.formData),
          3: () => tasksProductionApi.returnMaterials(this.formData),
          4: () => tasksProductionApi.useMaterials(this.formData),
        };

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500));
        await apis[this.showNum]();

        this.$message.success('操作成功');
        this.visible = false;
        this.$emit('success');
      } catch (error) {
        console.error('Operation Error:', error);
        this.$message.error('操作失败');
      } finally {
        this.confirmLoading = false;
      }
    },
    resetForm() {
      this.formData = {
        checkQuantity: null,
        checkNote: '',
        storeQuantity: null,
        storeNote: '',
        receiveQuantity: null,
        receiver: '',
        receiveNote: '',
        returnQuantity: null,
        returner: '',
        returnReason: '',
        returnNote: '',
        useQuantity: null,
        user: '',
        useNote: '',
      };

      this.$nextTick(() => {
        this.$refs.formRef?.resetFields();
      });
    },

    handleCancel() {
      this.visible = false;

      // 领料表单
      this.pickingForm = {
        storeNumber: 0,
        receiveNumber: 1,
        materialUnit: '',
        materialsId: '',
        productionStoreId: undefined,
        productionTaskId: '',
      };
    },
  },
});
</script>

<style lang="less" scoped>
.quantity-detail {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}
</style>
